package com.ocom.oauth.auth.app;

import com.alibaba.fastjson.JSON;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.RandomUtil;
import com.ocom.oauth.client.CompanyClientService;
import com.ocom.security.authentication.YoCiUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 说明：自定义的获取用户信息
 */
@Service
@Slf4j
public class AppCodeUserDetailService {

  @Autowired
  CompanyClientService companyClientService;

  @Autowired
  private RedisTemplate redisTemplate;


  @Value("${platformSecret}")
  private String platformSecret;


  public UserDetails loadByNameAndCode(String phone, String code) {
    String codeKey = "send:telephone:code:";
    String codeRedis = (String) redisTemplate.opsForValue().get(codeKey + phone);
    if (!StringUtils.equalsAny(code, "8888", "123456")) {
      if (!StringUtils.equals(code, codeRedis)) {
        throw new InvalidGrantException("验证码未通过验证");
      }
    }

    // 验证通过删除验证码
    if (!StringUtils.equalsAnyIgnoreCase(code, "123456", "8888")) {
      redisTemplate.delete(codeKey + phone);
    }

    Result userByNameAndRole = companyClientService.getUserByNameAndRole(phone, null);

    if (userByNameAndRole.getCode() != 200) {
      throw new UsernameNotFoundException("商户不存在");
    }

    EntityMngUserInfo entityMngUserInfo = JSON.parseObject(JSON.toJSONString(userByNameAndRole.getData()), EntityMngUserInfo.class);

    if (Objects.isNull(entityMngUserInfo)) {
      throw new UsernameNotFoundException("商户不存在");
    }

    if (!entityMngUserInfo.getStatus().equals(0)) {
      throw new InvalidGrantException("用户已被禁用");
    }
    List<Long> wxAdmin = new ArrayList<>();
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("ROLE_APP"));
    authorities.add(new SimpleGrantedAuthority("ROLE_WEB"));
    authorities.add(new SimpleGrantedAuthority("ROLE_WX"));

    Set<String> permissions = new HashSet<>();
    permissions.add("sys:user:admin");
    permissions.add("user:form:" + platformSecret);


    YoCiUser yoCiUser = new YoCiUser(entityMngUserInfo.getId(), (Long) entityMngUserInfo.getComId(),
        entityMngUserInfo.getRole(), String.valueOf(entityMngUserInfo.getId()), permissions, entityMngUserInfo.getUserName(),
        entityMngUserInfo.getPassword(),
        true, true, true, true, authorities, wxAdmin
        , entityMngUserInfo.getAreaId(), entityMngUserInfo.getBnsId(), entityMngUserInfo.getId(), 45l);
    yoCiUser.setForm(RandomUtil.generateNumber(30));
    //YoCiUser(entityMngUserInfo.getId(), Long.valueOf(entityMngUserInfo.getComId()),entityMngUserInfo.getRole() ,String.valueOf(entityMngUserInfo.getDeptId()), permissions,entityMngUserInfo.getUserName(), entityMngUserInfo.getPassword(), true, true, true, true, authorities,new ArrayList<>());
    return yoCiUser;

  }

}
